# This is a basic workflow to help you get started with Actions

name: SSH_DEPLOY

# Controls when the workflow will run
on:
  # Triggers the workflow on push or pull request events but only for the "main" branch
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  deploy:
    environment: testenv
    # The type of runner that the job will run on
    runs-on: ubuntu-latest

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      - name: Get current date
        id: date
        run: echo "::set-output name=date::$(date +'%Y-%m-%d_%H.%M.%S')"

      - name: test vars
        run: echo "${{ github.server_url }}/${{ github.repository }}"


      - name: Deploy code
        uses: appleboy/ssh-action@master
        env:
          PROJECT_DIR: ${{ steps.date.outputs.date }}
        with:
          host: ${{ vars.DEPLOY_HOST }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            cd /var/www/html
            rm -rf ${{ env.PROJECT_DIR }} 
            git clone ${{ github.server_url }}/${{ github.repository }}.git ${{ env.PROJECT_DIR }}
            cd /var/www/html/${{ env.PROJECT_DIR }}
            sh ./deploy.sh ${{ vars.DEPLOY_HOST }} ${{ secrets.MYSQL_HOST }} ${{ secrets.MYSQL_USER }} ${{ secrets.MYSQL_PASSWORD }} ${{ secrets.MYSQL_DATABASE }}
            rm -rf /var/www/html/${{ env.PROJECT_DIR }}/var/log
            mkdir -p /var/www/html/${{ env.PROJECT_DIR }}/var/log
            cd /var/www/html/${{ env.PROJECT_DIR }}
            ln -s /var/www/html/shared/log /var/www/html/${{ env.PROJECT_DIR }}/var/log
            mv -Tf /var/www/html/current /var/www/html/previous
            ln -s /var/www/html/${{ env.PROJECT_DIR }} /var/www/html/current
            
